# This file is part of Howlr.
#
# Howlr is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Howlr is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Howlr.  If not, see <http://www.gnu.org/licenses/>.

require 'action_mailer'

module Howlr::Deliverers
  class Base
    class_inheritable_accessor :protocol
  end

  class Email < Base
    self.protocol = 'mailto'
    
    def self.deliver(message, options = {})
      recipients = []
      message.recipients.each do |r|
        recipients << (r.respond_to?(:address) ? r.address : r)
      end
      
      Mailer.raise_delivery_errors = true
      
      begin
        Mailer.deliver_message(
          message.subject,
          recipients,
          message.from,
          message.body,
          message.content_type
        )
        return true
      rescue => e
        message.delivery_errors << e
        return false
      end
    end
    
    class Mailer < ::ActionMailer::Base
      # We use sendmail by default since it might just work out of the box.
      # You can of course override this by setting up ActionMailer as normal.
      self.delivery_method = :sendmail 
      self.template_root = File.dirname(File.expand_path(__FILE__))+'/..'
      self.raise_delivery_errors = true
      self.logger = $LOG
    
      def message(subject, recipients, from, contents, content_type = 'text/plain')
        self.content_type content_type
        self.recipients   recipients
        self.from         from
        self.subject      subject
        self.body         :contents => contents
      end
    end
  end

  class Snarl < Base
    self.protocol = 'snarl'
    
    def self.deliver(message, options = {})
    end
  end
end